package cc.catface.smsdemo.sendmsg;

import com.umpay.mascloud.mgw.service.webservice.server.WsSmsService;
import com.umpay.mascloud.mgw.service.webservice.server.WsSmsServiceService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @author: lyp
 * @Date: 2021/9/27 09:27
 * @Description: sms移动短信接口(webservice方式调用)
 */
public class SmsUtils {

    private static Logger logger = LoggerFactory.getLogger(SmsUtils.class);


    /**
     * 账号
     */
    private static String apId = "";
    /**
     * 密码
     */
    private static String secretKey = "";
    /**
     * 集团名称
     */
    private static String ecName = "";
    /**
     * 网关签名编码
     */
    private static String sign = "";
    /**
     * 拓展码（可以为空）
     */
    private static String addSerial = "";


    /**
     * 按EcName、apId、secretKey、mobiles
     * （拼起来，中间无空格如1380013800013800138001）、
     * content、sign、addSerial顺序拼接得到的字符串计算md5
     *
     * @param phone
     * @param content
     * @return
     */
    public static String getMac(String phone, String content) {
        // 按规则拼接mac
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(ecName);
        stringBuffer.append(apId);
        stringBuffer.append(secretKey);
        stringBuffer.append(phone);
        stringBuffer.append(content);
        stringBuffer.append(sign);
        stringBuffer.append(addSerial);
        // 按移动对接文档对mac进行加密
        return Md5Util2.MD5(stringBuffer.toString()).toLowerCase();
    }

    /**
     * <WsSubmitReq>
     * <apId>apId13</apId>
     * <secretKey>123</secretKey>
     * <ecName>测试</ecName>
     * <mobiles>
     * <string>13800138000</string>
     * <string>13800138001</string>
     * </mobiles>
     * <content>测试内容</content>
     * <sign>mysign</sign>
     * <addSerial>2134</addSerial>
     * <mac> 242c191105bbe62b203caf7a57afe7c6 </mac>
     * </WsSubmitReq>
     * 生成移动webservice想要的xml
     * todo 有待改进 后期可以根据需求决定是否支持短信和号码一对多
     *
     * @return
     */
    public static String genXmlStr(String mac, String phone, String content) {
        // 创建一个完整的节点
        Document doc = DocumentHelper.createDocument();
        Element wsSubmitReqElement = doc.addElement("WsSubmitReq");
        Element apIdElement = wsSubmitReqElement.addElement("apId");
        Element secretKeyElement = wsSubmitReqElement.addElement("secretKey");
        Element ecNameElement = wsSubmitReqElement.addElement("ecName");
        Element mobilesElement = wsSubmitReqElement.addElement("mobiles");
        Element stringElement = mobilesElement.addElement("string");
        Element contentElement = wsSubmitReqElement.addElement("content");
        Element signElement = wsSubmitReqElement.addElement("sign");
        Element addSerialElement = wsSubmitReqElement.addElement("addSerial");
        Element macElement = wsSubmitReqElement.addElement("mac");
        // 给每个节点赋值
        apIdElement.setText(apId);
        secretKeyElement.setText(secretKey);
        ecNameElement.setText(ecName);
        stringElement.setText(phone);
        contentElement.setText(content);
        signElement.setText(sign);
        addSerialElement.setText(addSerial);
        macElement.setText(mac);

        OutputFormat format = OutputFormat.createCompactFormat();
        StringWriter writer = new StringWriter();
        XMLWriter output = new XMLWriter(writer, format);

        try {
            output.write(doc);
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                writer.close();
                output.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }

        }
        return writer.toString();
    }

    /**
     * 发送短信
     * @param phone
     * @param content
     * @return
     */
    public static Boolean sendMsg(String phone, String content) {
        WsSmsServiceService wsSmsServiceService = new WsSmsServiceService();
        WsSmsService wsSmsServicePort = wsSmsServiceService.getWsSmsServicePort();
        String smsResponseXml = wsSmsServicePort.sendSms(genXmlStr(getMac(phone, content), phone, content));
        System.out.println("smsResponseXml；" + smsResponseXml);
        return parseSmsResponseXml(smsResponseXml);
    }

    public static void main(String[] args) {
        sendMsg("13012892925", "222");

    }

    /**
     * 解析中国移动响应的xml
     *
     * <SendSmsResponse>
     * <msgGroup>0927112828000001122046</msgGroup>
     * <rspcod>success</rspcod>
     * <success>true</success>
     * </SendSmsResponse>
     *
     * @param xmlStr
     * @return
     */
    public static Boolean parseSmsResponseXml(String xmlStr) {
        if (StringUtils.isNotBlank(xmlStr)) {
            Document doc;
            String success = null;
            // 将字符串转为XML
            try {
                doc = DocumentHelper.parseText(xmlStr);
                // 获取根节点
                Element rootElt = doc.getRootElement();
                success = rootElt.elementTextTrim("success");
            } catch (DocumentException e) {
                logger.error(e.getMessage());
            }
            return "true".equals(success);
        }
        return false;

    }
}
